package com.stake.web.controller;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.MessageFormat;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.zip.GZIPInputStream;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathFactory;

import org.apache.commons.cli.BasicParser;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.OptionBuilder;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;

import com.google.code.linkedinapi.client.LinkedInApiClient;
import com.google.code.linkedinapi.client.LinkedInApiClientException;
import com.google.code.linkedinapi.client.LinkedInApiClientFactory;
import com.google.code.linkedinapi.client.constant.ApplicationConstants;
import com.google.code.linkedinapi.client.constant.LinkedInApiUrls.LinkedInApiUrlBuilder;
import com.google.code.linkedinapi.client.oauth.LinkedInApiConsumer;
import com.google.code.linkedinapi.client.oauth.LinkedInOAuthService;
import com.google.code.linkedinapi.client.oauth.LinkedInOAuthServiceFactory;
import com.google.code.linkedinapi.schema.HttpHeader;
import com.google.code.linkedinapi.schema.Person;

public class LinkedInOauth {
	
	/**
     * Consumer Key
     */
    private static final String CONSUMER_KEY_OPTION = "consumerKey";
	
    /**
     * Consumer Secret
     */
    private static final String CONSUMER_SECRET_OPTION = "consumerSecret";
    
    /**
     * Name of the help command line option.
     */
    private static final String HELP_OPTION = "help";
    
    /**
	 * @param args
	 */
	public static void main(String[] args) {
		Options options = buildOptions();
        try {
        	String[] params = new String[]{"-consumerKey",  "8r3m2553p6z0", "-consumerSecret",  "zeBe9US0MKfx6PUV" };
            CommandLine line = new BasicParser().parse(options, params);
            processCommandLine(line, options);
        } catch(ParseException exp ) {
            System.err.println(exp.getMessage());
            printHelp(options);
        }
	}
	
    /**
     * Process command line options and call the service. 
     */
    private static void processCommandLine(CommandLine line, Options options) {
        if(line.hasOption(HELP_OPTION)) {
            printHelp(options);            
        } else if(line.hasOption(CONSUMER_KEY_OPTION) && line.hasOption(CONSUMER_SECRET_OPTION)) {
        	try {
        		final String consumerKeyValue = line.getOptionValue(CONSUMER_KEY_OPTION);
        		final String consumerSecretValue = line.getOptionValue(CONSUMER_SECRET_OPTION);
        		
        		
        		
        	/*	
        	 * final LinkedInOAuthService oauthService = new LinkedInOAuthServiceImpl(new LinkedInApiConsumer(consumerKeyValue, consumerSecretValue));
        	 * System.out.println("Fetching request token from LinkedIn...");
        		
        		LinkedInRequestToken requestToken = oauthService.getOAuthRequestToken();
        		
                String authUrl = requestToken.getAuthorizationUrl();

                System.out.println("Request token: " + requestToken.getToken());
                System.out.println("Token secret: " + requestToken.getTokenSecret());
                System.out.println("Expiration time: " + requestToken.getExpirationTime());

                System.out.println("Now visit:\n" + authUrl
                        + "\n... and grant this app authorization");
                System.out.println("Enter the PIN code and hit ENTER when you're done:");

                BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
                String pin = br.readLine();

                System.out.println("Fetching access token from LinkedIn...");
                
                LinkedInAccessToken accessToken = oauthService.getOAuthAccessToken(requestToken, pin);

                System.out.println("Access token: " + accessToken.getToken());
                System.out.println("Token secret: " + accessToken.getTokenSecret());*/

        		final LinkedInApiClientFactory factory = LinkedInApiClientFactory.newInstance(consumerKeyValue, consumerSecretValue);
        		final LinkedInApiClient client = factory.createLinkedInApiClient("a8ef2cf3-e368-4d6b-b7d5-0532774c2809", "4ebb4f02-28c9-4359-b25e-cf06d107b790");
        		
    			System.out.println("Fetching profile for current user.");
    			LinkedInApiUrlBuilder builder2 = new LinkedInApiUrlBuilder("http://api.linkedin.com/v1/people/~:(id,first-name,last-name,headline,picture-url,location)");
				String                apiUrl  = builder2.buildUrl();
				InputStream is = callApiMethod(apiUrl, new LinkedInApiConsumer(consumerKeyValue, consumerSecretValue), client);
				DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
	            domFactory.setNamespaceAware(true); // never forget this!
	            DocumentBuilder builder = domFactory.newDocumentBuilder();
	            Document doc = builder.parse(is);
	            XPath xpath = XPathFactory.newInstance().newXPath();
	            XPathExpression locExp = xpath.compile("//person/location/name/text()");
	            Object result = locExp.evaluate(doc, XPathConstants.NODESET);
	            NodeList nodes = (NodeList) result;
	            System.out.println(nodes.item(0).getNodeValue());
	            /*BufferedReader in = new BufferedReader(new InputStreamReader(is));
	            String inputLine;
	            while ((inputLine = in.readLine()) != null)
	                System.out.println(inputLine);
	            in.close();*/
	            
			} catch (Exception e) {
				e.printStackTrace();
			}
        } else {
            printHelp(options);
        }
    }
	
    
    /**
    *
    *
    * @param apiUrl
    * @param expected
    * @param httpHeaders
    *
    * @return
    */
   protected static InputStream callApiMethod(String apiUrl, LinkedInApiConsumer apiConsumer, LinkedInApiClient client) {
	   List<HttpHeader> httpHeaders = Collections.emptyList();
	   Map<String, String> requestHeaders = new HashMap<String, String>(); 
	   /** Field description */
	    final String GZIP_ENCODING = "gzip";
       // by default we compress contents
       requestHeaders.put("Accept-Encoding", "gzip, deflate");
	   int expected = HttpURLConnection.HTTP_OK; 
       try {
           LinkedInOAuthService oAuthService =
               LinkedInOAuthServiceFactory.getInstance().createLinkedInOAuthService(apiConsumer.getConsumerKey(),
                   apiConsumer.getConsumerSecret());
           URL               url     = new URL(apiUrl);
           HttpURLConnection request = (HttpURLConnection) url.openConnection();

           if (ApplicationConstants.CONNECT_TIMEOUT > -1) {
               request.setConnectTimeout(ApplicationConstants.CONNECT_TIMEOUT);
           }

           if (ApplicationConstants.READ_TIMEOUT > -1) {
               request.setReadTimeout(ApplicationConstants.READ_TIMEOUT);
           }

           for (String headerName : requestHeaders.keySet()) {
               request.setRequestProperty(headerName, requestHeaders.get(headerName));
           }
           
           for (HttpHeader header : httpHeaders) {
               request.setRequestProperty(header.getName(), header.getValue());
           }
           
           oAuthService.signRequestWithToken(request, client.getAccessToken());
           request.connect();

           if (request.getResponseCode() != expected) {
              System.out.println("Error Occourred"); 
              return null;
           } else {
               return getWrappedInputStream(request.getInputStream(),
                                            GZIP_ENCODING.equalsIgnoreCase(request.getContentEncoding()));
           }
       } catch (IOException e) {
           throw new LinkedInApiClientException(e);
       }
   }
   
   /**
    * Method description
    *
    *
    * @param is
    * @param gzip
    * @return
    * @throws IOException
    */
   protected static InputStream getWrappedInputStream(InputStream is, boolean gzip) throws IOException {
       if (gzip) {
           return new BufferedInputStream(new GZIPInputStream(is));
       } else {
           return new BufferedInputStream(is);
       }
   }
   
	/**
     * Build command line options object.
     */
    private static Options buildOptions() {
       
        Options opts = new Options();
        
        String helpMsg = "Print this message.";
        Option help = new Option(HELP_OPTION, helpMsg);
        opts.addOption(help);

        String consumerKeyMsg = "You API Consumer Key.";
        OptionBuilder.withArgName("consumerKey");
        OptionBuilder.hasArg();
        OptionBuilder.withDescription(consumerKeyMsg);
        Option consumerKey = OptionBuilder.create(CONSUMER_KEY_OPTION);
        opts.addOption(consumerKey);
        
        String consumerSecretMsg = "You API Consumer Secret.";
        OptionBuilder.withArgName("consumerSecret");
        OptionBuilder.hasArg();
        OptionBuilder.withDescription(consumerSecretMsg);
        Option consumerSecret = OptionBuilder.create(CONSUMER_SECRET_OPTION);
        opts.addOption(consumerSecret);
        
        return opts;
    }
    
    /**
     * Print help and usage.
     */
    private static void printHelp(Options options) {
        int width = 80;
        String syntax = LinkedInOauth.class.getName() + " <options>";
        String header = MessageFormat.format("\nBoth the -{0} and -{1} options are required.", CONSUMER_KEY_OPTION, CONSUMER_SECRET_OPTION);
        new HelpFormatter().printHelp(width, syntax, header, options, null, false);
    }
    
    /**
     * Print the result of API call.
     */
    private static void printResult(Person profile) {
    	System.out.println("================================");
    	System.out.println("Name:" + profile.getFirstName() + " " + profile.getLastName());
    	System.out.println("Headline:" + profile.getHeadline());
    	System.out.println("Summary:" + profile.getSummary());
    	System.out.println("Industry:" + profile.getIndustry());
    	System.out.println("Picture:" + profile.getPictureUrl());
    	System.out.println("id:" + profile.getId());
	}

}
